var ROWS = 15 ;//总格子行数
var COLS = 20;
var Rad = 37; //格子半径
var Width = 2*Rad;
var Height = Math.sqrt( 3 )* Rad;
var startX = Rad; //格子起点
var startY = Rad; //

var B_SIXMODE = true;
var Test = true;
var getDx=function(r){
    var dx = 0;
    if (r % 2 == 1){
        dx = Rad;
    }
    return dx
};
//根据行列 得到格子位置
var getPixel=function(r,c){
    var dx =  getDx(r)
    return cc.p(startX+dx+c*Width,startY+r*Height) 
};
// 初始化格子障碍物比率
var grade = 0;//游戏难度，初始化是0
var OB_RATE =  0.1 ;//比率越大 越简单
var CatNumber = 3;//猫咪个数 -- 默认就一只猫
var isCatTurn = false;//轮到神经猫操作
var PlayerCount = 3;//玩家一轮能下的次数
cc.animate = cc.Animate.create;
var itemRes = [res.chess0,res.chess1];
var GameLayer = cc.Layer.extend({
    ctor: function () {
        this._super();
        this.bIceTool = false;//是否使用冰冻
        this.nIceTool = 1;//冰冻道具个数
        if (B_SIXMODE) {
            this.initViewSix()
        } else {
            this.initView();
        }
        // 游戏难度
        this.initDifficulty();
        // 玩家指令信息
        this.initChatList();
        // 画出多边形的边界
        // this.initPolygonBoundary();
        // 画出游戏消息
        this.initIntroduce();
        // 更新指令
        this.updateChatList();
        this.loadAnimation();
        // 刷星排行榜
        this.rankViews =[];
        this.rankInfoViews = [];
        this.showRankList();
        this.initCats(CatNumber);
        // 当前狗子的个数
        this.initDogNumber();
        // 玩家能够下的次数
        this.initOptNum();
        // 是否轮到玩家下棋
        this.initHandleUser();
        // 背景音乐
        cc.audioEngine.playMusic(res.bgMusic,true);        
        gCtrl.game = this;//
        console.log("=====cc.winSize===" + cc.winSize.width + "," + cc.winSize.height);
        // 画梯形****************
        let size = cc.winSize;
        let leftBottomPolygon = [
            { x: 20, y: 20 },//左下点 起点
            { x: 500, y: 20 },//右下点
            { x: 200, y: 500 },//右上点
            { x: 20, y: 500 }]//左上点
        let node = gCtrl.createPolygonLines(leftBottomPolygon, cc.color(255, 0, 0, 255));
        this.addChild(node, 1000);
        let d = 3 / 5;//该梯形，每上升5个像素 宽度减少3
        let rightBottomPolygon = [
            { x: 1450, y: 20 },//左下点 起点
            { x: 1900, y: 20 },//右下点
            { x: 1900, y: 500 },//右上点
            { x: 1700, y: 500 },//左上点
        ]
        node = gCtrl.createPolygonLines(rightBottomPolygon, cc.color(255, 0, 0, 255));
        this.addChild(node, 1000);
        let leftTopPolygon = [
            { x: 20, y: 600 },//左下点 起点
            { x: 220, y: 600 },//右下点
            { x: 450, y: 1000 },//右上点
            { x: 20, y: 1000 },//左上点
        ]
        node = gCtrl.createPolygonLines(leftTopPolygon, cc.color(255, 0, 0, 255));
        this.addChild(node, 1000);
        let rightTopPolygon = [
            { x: 1700, y: 600 },//左下点 起点
            { x: 1900, y: 600 },//右下点
            { x: 1900, y: 1000 },//右上点
            { x: 1450, y: 1000 },//左上点
        ]
        node = gCtrl.createPolygonLines(rightTopPolygon, cc.color(255, 0, 0, 255));
        this.addChild(node, 1000);
        // 画梯形****************
        // 划线****************
        // for (var i = 0; i < 8; i++) {
        //     let dy = 50 * i + 50;
        //     dx = dy * d;
        //     let line = gCtrl.createLine(20, 20 + dy, 490 - dx, 20 + dy, 3);
        //     line.setColor(cc.color(0, 0, 255, 255));
        //     node.addChild(line);
        // }
        // for (var i = 0; i < 8; i++) {
        //     let dy = 50 * i + 50;
        //     dx = dy * d;
        //     let line = gCtrl.createLine(1450 + dy / 2, 20 + dy, 1900, 20 + dy, 3);
        //     line.setColor(cc.color(0, 0, 255, 255));
        //     node.addChild(line);
        // }
        // for (var i = 0; i < 8; i++) {
        //     let dy = 50 * i + 50;
        //     dx = dy * d;
        //     let line = gCtrl.createLine(20, 600 + dy, 220 + dx, 600 + dy, 3);
        //     line.setColor(cc.color(0, 0, 255, 255));
        //     node.addChild(line);
        // }
        // for (var i = 0; i < 8; i++) {
        //     let dy = 50 * i + 50;
        //     dx = dy * d;
        //     let line = gCtrl.createLine(1450+ dx, 1000 - dy, 1900 , 1000 - dy, 3);
        //     line.setColor(cc.color(0, 0, 255, 255));
        //     node.addChild(line);
        // }
        // 划线****************
    },

    updateDifficulty:function(){
        let difficult = grade;
        // 游戏成功 等级+1，当等级为5 重置为0
        difficult++;
        if (difficult > 5) {
            difficult = 1;
        }
        grade = difficult;
    },
    onGetHuyaMessage:function(data){
        //对应点击事件
        if(isCatTurn){
            return;
        }
        let content = data.content;
        let number = Number(content)
        if(isNaN(number)){
            return;
        }
        console.log("onGetHuyaMessage number:"+number);
        if(number>=1 && number<=this.chessCount){
            if(this.clickCell(number)){
                gCtrl.addCurrentUser(data);
                this.updateChatList();
            }
        }
    },
    initHandleUser:function(){
        let size = cc.winSize;
        // 标题
        if (!this.handleInfo) {            
            let handleInfo = new cc.LabelTTF("轮到:", "微软雅黑", 30);
            handleInfo.setColor(0,0,255,1);
            handleInfo.x = 70;
            handleInfo.y = 380;
            this.addChild(handleInfo);
            this.handleInfo = handleInfo;
        }
        if (!isCatTurn) {            
            let hadnleIcon = new cc.Sprite(res.aiHandle);
            // 图片
            this.addChild(hadnleIcon);
            hadnleIcon.x = 150;
            hadnleIcon.y = 320;
            hadnleIcon.scale = 3;
            this.hadnleIcon = hadnleIcon;
        } else {
            this.hadnleIcon.removeFromParent();
            this.hadnleIcon = null;
            delete this.hadnleIcon;
        }
    },
    initOptNum:function(){
        let size = cc.winSize;
        if (!this.dogNumber) {            
            let dogNumber = new cc.LabelTTF("可以移动的次数:" + this.nClickCount + "/" + PlayerCount, "微软雅黑", 30);
            dogNumber.setColor(0,0,255,1);
            dogNumber.x = 160;
            dogNumber.y = 240;
            this.addChild(dogNumber);
            this.dogNumber = dogNumber;
        } else{
            this.dogNumber.string = `可以移动的次数:${this.nClickCount}/${PlayerCount}`;
        }
    },
    initDogNumber:function(){
        let size = cc.winSize;
        let dogNumber = new cc.LabelTTF("当前狗子数:" + CatNumber, "微软雅黑", 30);
        dogNumber.setColor(0,0,255,1);
        dogNumber.x = 120;
        dogNumber.y = 180;
        this.addChild(dogNumber);
    },
    initView : function(){
        //
        let size = cc.winSize;
        let offsetY = 85;
        let topY = size.height-80;
        let sprite = new cc.Sprite(res.gamebg);
        this.addChild(sprite);
        sprite.x = size.width/2;
        sprite.y = size.height/2;
        sprite.scaleX = size.width/120;
        sprite.scaleY = size.height/120;
        // 棋牌
        this.blocks = new cc.Node();//触碰移动节点
        this.blocks.x = 0;
        this.blocks.y = 0;
        this.blocks.setContentSize(cc.winSize.width,cc.winSize.height);
        this.addChild(this.blocks);
        var lables = [];
        for (var i = 0; i < ROWS; i++) {
            for (var j = 0; j < COLS; j++) {
                //添加空棋子
                var cell = new cc.Sprite(res.chess0);
                this.blocks.addChild(cell);
                var pt = getPixel(i,j);
                cell.x = pt.x;
                cell.y = pt.y;
                var lable = new cc.LabelTTF(""+(i*COLS+j+1), "微软雅黑", 30);
                lable.x = cell.x;
                lable.y = cell.y-5;
                this.blocks.addChild(lable, 2);
                lables[i*COLS+j] = lable;
                if(i==0||j==0||i==ROWS-1||j==COLS-1){
                    cell.setColor(cc.color(0,255,0));
                }
                
            }
        }
        this.blocks.y = 0;
        this.lables = lables;
        let number = new cc.LabelTTF("当前步数:0", "微软雅黑", 30);
        number.x = size.width-30;
        number.y = size.height - 60;
        number.anchorX =1;
        this.addChild(number);
        this.currentNumber = number;
    },
    //更新玩家指令信息
    updateChatList:function(){
        this.cleanChatList();
        if(Test){
            let list = [];
            for (var i = 0; i < 20; i++) {
                let data = {sendNick:Mock.mock('@cword(1,10)')+Math.floor(Math.random()*10000),
                point:Math.floor( Math.random()*10000 ),
                content:Math.floor( Math.random()*10000 ),
            };

                list.push(data)
            }
            // list.push({
            //     sendNick:"你好11123",
            //     point:100
            // })
            gCtrl.chatList = list;
        }
        let size = cc.winSize;
        let chatList = window.gCtrl.chatList;
        if (chatList.length > 0) {        
            let d = 4 / 8;//该梯形，每上升5个像素 宽度减少3
            // 清空
            // 长度过滤器
            if (chatList.length > 9) {
                chatList = chatList.slice(0,9);
            }
            for (let index = 0; index < chatList.length; index++) {
                const rankItem = chatList[index];
                // 开始绘制
                let name = "";
                if (rankItem) {                    
                    if (rankItem['sendNick']) {
                        
                         name = rankItem.sendNick;
                        if (name.length > 3+index) {
                            name = name.slice(0,2+index) + '...';
                        }
                    } else {
                        name = rankItem.sendNick;
                    }
                }else{
                    return;
                }
                let rank = new cc.LabelTTF(name , "微软雅黑", 30);
                rank.setColor(0,0,255,1);
                rank.y = size.height/2 - 50 - (index + 1) * 50;
                let dy = 30 * index + 30;
                dx = dy * d;
                rank.x = size.width-170 - dy
                rank.anchorX =0;
                this.addChild(rank);
                this.chatViews.push(rank);
                // label分离
                let content = new cc.LabelTTF(rankItem.content, "微软雅黑", 30);
                content.y = size.height/2 - 50 - (index + 1) * 50;
                content.x = size.width-60;
                content.setColor(0,0,255,1);
                this.addChild(content);
                this.chatViews.push(content);
            }
        }
    },
    initChatList:function(){
        let size = cc.winSize;
        // let chatList = window.gCtrl.chatList;
        let info = new cc.LabelTTF("玩家指令", "微软雅黑", 50);
        info.x = size.width-50;
        info.y = size.height/2 ;

        info.anchorX =1;
        // this.addChild(info);
    },
    initIntroduce:function(){
        let size = cc.winSize;
        let info = new cc.LabelTTF("发送弹幕【棋子编号】\n围住小狗，让小狗无\n路可走，越快围\n住积分越高，\n不要让\n小狗\n逃", "微软雅黑", 30);
        info.setColor(0,0,255,1);
        info.x = 200;
        info.y = size.height - 280;
        this.addChild(info);
    },
    // 画几何图形
    initPolygonBoundary: function () {
        let size = cc.winSize;
        // 左下角梯形****************
        let x  = 10;
        let y = size.height/2-50;
        let topWdith = 200;//上底
        let bottomWdith = 400;//下底
        let bottomLeftLayer = this.producetPolygonPoint(x,y,topWdith,bottomWdith);
        this.addChild(bottomLeftLayer);
        // 左下角梯形****************
        // 左上角梯形****************
        let topLeftLayer = this.producetPolygonPoint(x,y,topWdith,bottomWdith);
        //  旋转、摆位置
        topLeftLayer.setRotationX(180);
        topLeftLayer.setPosition(new cc.Point(10,size.height));
        this.addChild(topLeftLayer);
        // 左上角梯形****************
        // 右上角****************
        let topRightLayer = this.producetPolygonPoint(x,y,topWdith,bottomWdith);
        topRightLayer.setRotation(180);
        topRightLayer.setPosition(new cc.Point(size.width,size.height));
        this.addChild(topRightLayer);
        // 右上角****************
        // 右下角****************
        let bottomRight = this.producetPolygonPoint(x,y,topWdith,bottomWdith);
        bottomRight.setPosition(new cc.Point(size.width,0));
        bottomRight.setRotationY(180);
        this.addChild(bottomRight);
        // 右下角****************
    },
    /**
     * @description: 画出一个梯形
     * @param {Number} x 四边形左上角的坐标
     * @param {Number} y
     * @param {Number} topWdith 上底
     * @param {Number} bottomWdith 下底
     * @return {cc.Node} 返回的节点
     */
    producetPolygonPoint:function(x,y,topWdith,bottomWdith){
        let container = new cc.Node();
        // 线条粗
        let solid = 5;
        // 侧边长:取小的，靠外
        let sideLength = topWdith > bottomWdith ? topWdith : bottomWdith;
        // 斜边长：斜边靠里
        let hypotenuseLength = Math.abs(topWdith - bottomWdith);
        hypotenuseLength = Math.sqrt(hypotenuseLength*hypotenuseLength + sideLength*sideLength);
        //画出四条边*******************
        // 四条边
        let layers = [];
        // 上底
        layers.push(new cc.LayerColor(cc.color(0, 0, 0, 150),topWdith,solid));
        // 下底
         layers.push(new cc.LayerColor(cc.color(0, 0, 0, 150),bottomWdith,solid));
        //  侧边
         layers.push(new cc.LayerColor(cc.color(0, 0, 0, 150),sideLength,solid));
        //  斜边
         layers.push(new cc.LayerColor(cc.color(0, 0, 0, 150),hypotenuseLength,solid));
          //画出四条边*******************
        //  锚点全部为0
        layers.forEach(function (layer) {
            layer.setAnchorPoint(new cc.Point(0,0));
        });
         // 确定四个点位置*****************
        // 上底
        let topLayer = layers[0];
        topLayer.setPosition(new cc.Point(x,y));
        // 下底
        let bottomLayer = layers[1];
        bottomLayer.setPosition((new cc.Point(x,y - sideLength)));
        // 侧边
        let sideLayer = layers[2];
        sideLayer.setPosition((new cc.Point(x,y)));
        sideLayer.setRotation(90);
        // 斜边
        let hypotenuseLayer = layers[3];
        hypotenuseLayer.setPosition((new cc.Point(x + topWdith,y)));
        let a =  Math.abs(topWdith - bottomWdith) ;
        // 小角
        let deg = Math.asin(a / hypotenuseLength);
        hypotenuseLayer.setRotation(90 - deg * 180 / Math.PI);
         // 确定四个点位置*****************
        // 挂载
        for (let index = 0; index < layers.length; index++) {
            container.addChild(layers[index]);
        }
        return container;
    },
    cleanChatList:function name() {
        if (!this.chatViews) {
            this.chatViews = [];
        }
        for (var i = 0; i < this.chatViews.length; i++) {
            let node = this.chatViews[i];
            node.removeFromParent();
        }
        this.chatViews = [];
    },
    updateRankList:function(){
        let userInfos = gCtrl.userInfos;//全局保存用户信息
        let currentRoundUsers=gCtrl.currentRoundUsers;
        let rankList =[];
        for (var i = 0; i < currentRoundUsers.length; i++) {
            let uid =currentRoundUsers[i];
            let user = userInfos[uid];
            user.point = user.point+this.getIntegral(this.steps);
            rankList.push(user);
        }
        rankList.sort(function (a, b) {
            return b.point - a.point;
        })
        gCtrl.rankList = rankList;
    },
    showRankList:function(){
        this.clearRankList();
        if(Test){
            let list = [];
            for (var i = 0; i < 20; i++) {
                let data = {sendNick:Mock.mock("@cword(1,10)")+Math.floor(Math.random()*10000),
                point:Math.floor( Math.random()*10000 )};

                list.push(data)
            }
            // list.push({
            //     sendNick:"你好11123",
            //     point:100
            // })
            gCtrl.rankList = list;
        }

        // 开始绘制排行榜********************
        let size = cc.winSize;//窗口尺寸 
        let rankList = gCtrl.rankList;
        // 长度过滤器
        if (rankList.length>8) {
            rankList = rankList.slice(0,8);
        }
        if (rankList.length > 0) {
            let d = 1 / 5;//该梯形，每上升5个像素 宽度减少3
            for (let index = 0; index < 8; index++) {
                const rankItem = rankList[index];
                // 开始绘制排行榜
                // 对用户名进行剪裁
                let name = "";
                if (rankItem) {                    
                    if (rankItem['sendNick']) {
                        
                         name = rankItem.sendNick;
                        if (name.length > 3+index) {
                            name = name.slice(0,1+8 - index) + '...';
                        }
                    } else {
                        name = rankItem.sendNick;
                    }
                } else {
                    return;
                } 
                let rank = new cc.LabelTTF(name, "微软雅黑", 30);
                rank.setColor(0,0,255,1);
                rank.y = size.height - 60 - (index + 1) * 50;
                let dy = 30 * index + 30;
                dx = dy * d;
                rank.x = 1460 + dy
                rank.anchorX = 0;
                this.addChild(rank);
                this.rankViews[index] = (rank);
                // 两个label rankItem.point
                let userNameLabel = new cc.LabelTTF(rankItem.point ? rankItem.point : '0' , "微软雅黑", 30);
                userNameLabel.setColor(0,0,255,1);
                userNameLabel.x = 1850;
                userNameLabel.y = size.height - 60 - (index + 1) * 50;
                this.addChild(userNameLabel);
                this.rankInfoViews[index] = (rank);
            }
            
        }
    },
    clearRankList:function(){
        for (var i = 0; i < this.rankViews.length; i++) {
            this.rankInfoViews = [];
            let node = this.rankViews[i];
            this.rankInfoViews = [];
            node.removeFromParent();
        }
        for (var i = 0; i < this.rankInfoViews.length; i++) {
            let node = this.rankInfoViews[i];
            node.removeFromParent();
        }
        this.rankViews = [];
        this.rankInfoViews = [];
        this.rankInfoViews = [];
    },
    // 计算积分
    getIntegral:function(steps){
        // 判断输赢   
        let integral = 100;
        integral = integral - steps*2;
        if (integral < 5) {
            integral = 5;
        } 
        return integral;
    },
    initViewSix:function(){
        let size = cc.winSize;
        let sprite = new cc.Sprite(res.gamebg);
        this.addChild(sprite);
        sprite.x = size.width/2;
        sprite.y = size.height/2;
        sprite.scaleX = size.width/120;
        sprite.scaleY = size.height/120;
        // 棋盘
        this.blocks = new cc.Node();
        this.blocks.x = 180;
        this.blocks.y = 50;
        this.blocks.setContentSize(cc.winSize.width,cc.winSize.height);
        this.addChild(this.blocks);
        var lables = [];
        var centerRow = Math.floor(ROWS/2);
        var chessIndex = 1;
        this.edges = [];
        for (var i = 0; i < ROWS; i++) {
            var offset = Math.abs(i-centerRow);
            var beginCol = Math.floor((offset+1)/2); 
            var endCol = COLS-Math.floor(offset/2);
            for (var j = beginCol; j < endCol; j++) {
                //添加空棋子
                var cell = new cc.Sprite(res.chess0);
                this.blocks.addChild(cell);
                var pt = getPixel(i,j);
                cell.x = pt.x;
                cell.y = pt.y;
                cell.row = i;
                cell.col = j;
                cell.tag = chessIndex;
                var lable = new cc.LabelTTF(""+chessIndex, "微软雅黑", 30);
                lable.x = cell.x;
                lable.y = cell.y-5;
                this.blocks.addChild(lable, 1);
                lables[i*COLS+j] = lable;
                chessIndex ++;
                if(i==0||i==ROWS-1||j==beginCol||j==endCol-1){
                    this.edges.push({
                        row:i,
                        col:j
                    });
                    cell.setColor(cc.color(0,255,0));
                }
            }
        }
        this.chessCount = chessIndex-1;
        this.lables = lables;
        let number = new cc.LabelTTF("当前步数:0", "微软雅黑", 30);
        number.setColor(0,0,255,1);
        number.x = 180;
        number.y = size.height/2 - 100;
        number.anchorX =1;
        this.addChild(number);
        this.currentNumber = number;
        // 排行榜提示
        let rankInfo = new cc.LabelTTF("排行榜", "微软雅黑", 50);
        rankInfo.setColor(0,0,255,1);
        rankInfo.x = size.width-150;
        rankInfo.y = size.height - 50;
        rankInfo.anchorX =1;
        this.addChild(rankInfo);
    },
    initDifficulty:function(){
        this.updateDifficulty();
        let  difficult = grade ;//默认为2,范围：0-5
        let size = cc.winSize;
        // 障碍物的数量
        // 那就等级1是 24  等级2 ：20   等级3:18  等级4:15  等级5: 15
        switch (difficult) {
            case 1:
                OB_RATE = 0.24;
                break;
            case 2:
                OB_RATE = 0.20;
                break;
            case 3:
                OB_RATE = 0.18;
                break;
            case 4:
                OB_RATE = 0.15;
                break;
            case 5:
                OB_RATE = 0.15;
                break;
            default:
                OB_RATE = 0.1;
                break;
        }
        //渲染**************
        // 提示信息
        let info = new cc.LabelTTF("当前难度:", "微软雅黑", 30);
        info.setColor(0,0,255,1);
        info.x = 160;
        info.y = 120;
        info.anchorX =1;
        this.addChild(info);
        // 星星标记
        let difficultResIndex = `difficulty${difficult}`;
        let sprite = new cc.Sprite(res[difficultResIndex]);
        this.addChild(sprite);
        sprite.x = 160;
        sprite.y = 60;
         //渲染**************
    },
    getAIGrade:function(){
        let difficult = grade;//获得难度等级
        let AIGrade = 0;//AI安度等级
        switch (difficult) {
            case 5:
                AIGrade = 3; //100%困难
                break;
            case 4:
                AIGrade = Math.random()>0.5 ? 3 : 2;
                break;
            case 3:
                AIGrade = 2;
                break;
            case 2:     
                AIGrade = Math.random()>0.5 ? 2 : 1;
                break;
            case 1:
                AIGrade = 1;
                break;
            default:
                AIGrade = 1;
                break;
        }
        AIGrade = parseInt(AIGrade);
        return AIGrade;
    },
    onReStartGame:function(sender){
        isCatTurn = false;
        var game = new GameScene();
        cc.director.runScene(game);
        cc.audioEngine.playEffect(res.start);
    },
    onIceClick:function(sender){
        if(this.nIceTool <=0){return;}
        this.nIceTool = this.nIceTool -1;
        var self = this;
        let seq = cc.Sequence.create(
            cc.ScaleTo.create(0.1,0.9),
            cc.ScaleTo.create(0.1,1),
            cc.CallFunc.create(function(){
                sender.setColor(cc.color(128,128,128))
            })
        )
        //let repeat = cc.RepeatForever.create(seq);
        sender.runAction( seq);
        this.bIceTool = true;
        this.frozenCat(0);
        cc.audioEngine.playEffect(res.clickice);
    },
    loadAnimation:function () {
        //添加动画
        // var tex = cc.textureCache.addImage(res.player);
        var rect = cc.rect(0, 0, 112, 225);
        var movingFrames = [];
        // for (let i = 0; i < 16; i++) {
        //     rect.x = 0 + (i%4) * 61;
        //     rect.y = Math.floor(i/4)*93
        //     let frame = new cc.SpriteFrame(tex, rect);
        //     movingFrames.push(frame);
        // }
        // this.movingFrames = movingFrames;
        let anis =[res.ani1,res.ani2,res.ani3];
        //for (let i = 0; i < 16; i++) {
            var tex = cc.textureCache.addImage(anis[0]);
            let frame = new cc.SpriteFrame(tex,rect);
            movingFrames.push(frame);

            tex = cc.textureCache.addImage(anis[0]);
            frame = new cc.SpriteFrame(tex,rect);
            movingFrames.push(frame);

            tex = cc.textureCache.addImage(anis[1]);
            frame = new cc.SpriteFrame(tex,rect);
            movingFrames.push(frame);

            tex = cc.textureCache.addImage(anis[2]);
            frame = new cc.SpriteFrame(tex,rect);
            movingFrames.push(frame);

            tex = cc.textureCache.addImage(anis[2]);
            frame = new cc.SpriteFrame(tex,rect);
            movingFrames.push(frame);

            tex = cc.textureCache.addImage(anis[1]);
            frame = new cc.SpriteFrame(tex,rect);
            movingFrames.push(frame);

        //}
        this.movingFrames = movingFrames;
    },
    initCats:function(count){
      
        //小猫颜色--可以添加多点数据
        var color = [
            cc.color(255,255,255),
            cc.color(250,0,0),
            cc.color(250,128,120),
            cc.color(0,255,0),
            cc.color(120,250,120),
            cc.color(0,0,250),
            cc.color(120,120,250)
        ];
        var cats = [];
        for (var i = 0; i < count; i++) {
            var cat = new cc.Sprite(this.movingFrames[0]);
            //cat.scale = 0.1;
            var movingAnimation = new cc.Animation(this.movingFrames, 0.1+Math.random()*0.5);
            var movingAction = cc.animate(movingAnimation).repeatForever();
            cat.runAction(movingAction);
            cat.tag = 10000+i;
            this.blocks.addChild(cat, 1);
            cat.setColor(color[i%color.length]);
            cat.anchorY =0.3;
            cat.scale = 0.8;
            cats[i] = cat;
            var r =Math.floor(ROWS/2);
            var c =Math.floor(COLS/2+i);
            var lable = this.lables[r*COLS+c];
            cat.x = lable.x;
            cat.y = lable.y+30;
            cat.isLost = false;//是否被围住
            cat.steps = 0;//被围住的步数
        }
        this.cats = cats;
    },
    //设置格子成障碍物
    setObstacle:function(row,col,index){
        var lable = this.lables[row*COLS+col];
        var pos = row*COLS+col;
        var hasCat = false;
        this.cats.forEach(function (cat) {
            if (cat.pos == pos) {
                hasCat = true;
            } 
        });
        if (hasCat) {
            return false;
        }
        if(lable){
            // lable.setString("");  
        } 
        var icon = this.blocks.getChildByTag(1000+row*COLS+col);
        if(icon){
            icon.removeFromParent();
        }
        var sprite = new cc.Sprite(itemRes[index]);
        sprite.setLocalZOrder(1000);
        this.blocks.addChild(sprite);
        var pt = getPixel(row,col);
        sprite.x = pt.x;
        sprite.y = pt.y;
        sprite.tag = 1000+row*COLS+col;
        this.map[row][col] = index;
    },
    //游戏开始进入入口
    onEnter : function () {
        this._super();
        this.steps = 0;
        this.nClickCount = PlayerCount;
        this.initOptNum();
        this.map = [];
        this.randomCeil();
        // 刷新排行榜
        this.rankViews =[];
        this.rankInfoViews = [];
        // this.showRankList();
    },
    shuffle:function (arr) {  
        var i = arr.length, t, j; 
        while (i) { 
            j = Math.floor(Math.random() * i--); 
            t = arr[i]; 
            arr[i] = arr[j]; 
            arr[j] = t; 
        } 
        return arr;
    },
    randomCeilSix:function(){

        for (var i = 0; i < ROWS; i++) {
            this.map[i] = [];
            for (var j = 0; j < COLS; j++) {
                this.map[i][j] =0;
            }
        }

        var nCount = this.chessCount*OB_RATE;
        let arr = [];
        for (var i = 0; i < this.chessCount; i++) {
            arr[i] =i+1;
        }
        arr = this.shuffle(arr);
        for (var i = 0; i < nCount; i++) {
            let index = arr[i];
            let chess = this.blocks.getChildByTag(index);
            this.setObstacle(chess.row,chess.col,1);
        }
        this.randomCatPos();
    },

     //随机部分格子成障碍物
    randomCeil : function(){
        if(B_SIXMODE){
            this.randomCeilSix();
            return;
        }
        var nCount = COLS*ROWS;
        for (var i = 0; i < ROWS; i++) {
            this.map[i] = [];
            for (var j = 0; j < COLS; j++) {
                this.map[i][j] =0;
                var num = Math.floor(Math.random()*nCount);
                if(num<nCount*OB_RATE){
                    this.setObstacle(i,j,1);  
                }
            }
        }
        this.randomCatPos();
    },
    randomCatPos:function(){
        //坐标从中心向外围
        let locations =[123,122,124,103,104,142,143,125,105,121]  
        for (var i = 0; i < CatNumber; i++) {

            var num = locations[i%locations.length];
            var cell = this.blocks.getChildByTag(num);
            var r =cell.row;
            var c =cell.col;
            this.showCatPos(i,r*COLS+c);
            var block = this.blocks.getChildByTag(r*COLS+c+1000);
            if(block){
                block.removeFromParent();
            }
            this.map[r][c] =0;
        }
    },

    showCatPos:function(id,pos){//id：猫咪id
        console.log("showCatPos",id,pos);
        var lable = this.lables[pos];
        this.cats[id].x = lable.x;
        this.cats[id].y = lable.y+30;
        this.cats[id].pos = pos;
        this.cats[id].setLocalZOrder(10000-this.cats[id].y)
    },
    frozenCat:function(id){
        this.cats[id].stopAllActions();
        this.cats[id].setColor(cc.color(128,128,128));

        this.cats[id].runAction(cc.ScaleTo.create(0.5,0.6));
    },
    unFrozenCat:function(id){
        this.cats[id].setColor(cc.color(255,255,255));
        var movingAnimation = new cc.Animation(this.movingFrames, 0.2);
        var movingAction = cc.animate(movingAnimation).repeatForever();
        this.cats[id].runAction(movingAction);

        let seq = cc.Sequence.create(
            cc.ScaleTo.create(0.5,1),
            cc.ScaleTo.create(0.2,0.7),
            cc.ScaleTo.create(0.3,0.8)
        )
        this.currentNumber.runAction(seq);

        this.cats[id].runAction(seq);
    },
    //点击格子
    clickCell:function(number){
        let ceil = this.blocks.getChildByTag(number);
        var row = ceil.row;
        var col = ceil.col;
        var pos = row*COLS+col;
        var hasCat = false;
        this.cats.forEach(function (cat) {
            if (cat.pos == pos) {
                hasCat = true;
            } 
        });
        if (hasCat) {
            return false;
        }
        if(this.map[row][col]==1){
            //当前位置已经有障碍物
            //播放错误音效
            cc.audioEngine.playEffect(res.sounderror);
            return false;
        }
        this.setObstacle(row,col,1);
        if(this.bIceTool){
            this.bIceTool = false;
            this.unFrozenCat(0);
            cc.audioEngine.playEffect(res.frozen);
            return;
        }
        cc.audioEngine.playEffect(res.clickcell);
        // 添加点击次数控制
        this.nClickCount = this.nClickCount-1;
        this.initOptNum();
        //检测是否全部都没格子走
        if(this.checkIsSurround()){
            //---全部被围住------???要添加积分
            this.showWin();
            return true;
        }
        if(this.nClickCount==0){
            isCatTurn = true;//轮到狗走路
            this.initHandleUser();
            //0.3秒 ai开始计算  schedule：计时器
            this.catIndex = 0;//第一只猫运算开始
            this.schedule(this.startAI, 0.3);  
            this.steps += 1;
            this.showSteps(); 
            this.nClickCount = PlayerCount
            this.initOptNum();
        }
        return true;
    },
    showSteps:function(){
        this.currentNumber.setString("当前步数:"+this.steps);
        let seq = cc.Sequence.create(
            cc.ScaleTo.create(0.2,1.1),
            cc.ScaleTo.create(0.1,0.9),
            cc.ScaleTo.create(0.3,1)
        )
        this.currentNumber.runAction(seq);
    },
    isCatOut:function(cell){
        if(B_SIXMODE){
            for (var i = 0; i < this.edges.length; i++) {
                let data = this.edges[i];
                if(data.row==cell.x && data.col==cell.y){
                    return true;
                }
            }
            return false;
        }

        if ( cell.x==0 || cell.y==0 || cell.x ==ROWS-1 || cell.y == COLS-1 ) {
            return true;
        }
        return false;
    },
    //判断小狗是否被围住
    checkIsSurround:function(){
        // 邻边六个方向的位置坐标
        var direction0 =[[1,0],[1,1],[0,-1],[0,1],[-1,0],[-1,1]]; // 偶数
        var direction1 =[[1,-1],[1,0],[0,-1],[0,1],[-1,-1],[-1,0]];//奇数

        let map = this.map;

        var isInMap = function(x,y){
            if( x >= 0 && x < ROWS &&
                y >= 0 && y < COLS &&
               map[x][y]==0 
            ) {return true;}
            return false;
        }
        let cats = this.cats;

        var isCatPos = function(x,y){
            for (var i = 0; i < cats.length; i++) {
                let cat = cats[i];
                if(x*COLS+y == cat.pos){
                    return true;
                }
            }
            return false;
        }


        //6个方向的格子
        var getNeighbors = function(x,y){
            var neighbors = [];
            var dir = direction0;
            if(x%2==0){
                dir = direction1;
            }
            for (let i=0;i<6;i++){//-针对每个子节点 
                let nextX = x + dir[i][0];
                let nextY = y + dir[i][1];  
                if (isInMap(nextX,nextY) && !isCatPos(nextX,nextY)){
                    neighbors.push({x:nextX,y:nextY});
                }
            }
            return neighbors;
        }

        for (var i = 0; i < cats.length; i++) {
            let cat = cats[i];
            if(cat.isLost||cat.isOut)continue;
            let pos = cat.pos;
            let x = Math.floor(pos/COLS) 
            let y = pos%COLS
            //--- 附近6个格子是否有0
            let neighbors =getNeighbors(x,y)
            if(neighbors.length>0){
                return false;
            } 
        }
        return true;
    },

    //开始运算
    startAI:function(){
        this.unschedule(this.startAI);
        //检测是否越界
        if(this.catIndex>=CatNumber){
            isCatTurn = false;//可以监听弹幕，轮到观众下棋
            this.initHandleUser();
            return;
        }

        let currentCat = this.cats[this.catIndex];  
        if(currentCat.isLost || currentCat.isOut){
            //已经被围住或者逃跑 不用再计算 
            this.catIndex = this.catIndex +1;
            this.schedule(this.startAI, 0.1);
            return;
        }
        //------已经胜利---结束------
        let catPos = currentCat.pos;
        var rt = getNextDirection(catPos,this.map,ROWS,COLS,this.getAIGrade(),this.edges);
        // result-2:成功围住 ，1：围住了，小猫还有可以的格子  0：可以走
        if(rt.result==2){
            console.log("成功围住："+this.catIndex+",步数:"+this.steps);
            if(this.checkWin(this.catIndex,this.steps)){
                this.showWin();
                return;
            }
        }
        var cell = rt.cell;
        if(rt.result==0){
            // 神经猫逃脱
            if(this.isCatOut(cell)){
                currentCat.isOut = true;//逃跑的标志
                console.log("=======逃跑了====");
                //this.showLose();
                //return;
            }
            var pos = cell.x*COLS+cell.y;
            this.showCatPos(this.catIndex,pos);
            this.catIndex = this.catIndex +1;
            cc.audioEngine.playEffect(res.jump);  
        }

        if(rt.result==1){
            var pos = cell.x*COLS+cell.y;
            this.showCatPos(this.catIndex,pos);
            this.catIndex = this.catIndex +1;
            cc.audioEngine.playEffect(res.jump);
        }

        // 开始下个猫运算
        if(this.catIndex <CatNumber ){
            this.schedule(this.startAI, 0.4);
        }else{
            isCatTurn = false;
            this.initHandleUser();
        }
    },
    // 检测是否胜利 -- 所有的狗都lost
    checkWin:function(catIndex,n){
        //dog 动画停止 变小
        let dog = this.cats[catIndex];
        dog.isLost = true;
        dog.steps = n;
        dog.stopAllActions();
        dog.setColor(cc.color(128,128,128));
        dog.runAction(cc.ScaleTo.create(0.5,0.6));
        //--添加积分
        this.updateRankList();
        this.showRankList();
        //检测是全部被围住
        for (var i = 0; i < this.cats.length; i++) {
            let cat = this.cats[i];
            if(!cat.isLost){
                return false;
            }

        }
        return true;
    },

    showWin:function(){
        let size = cc.winSize;
        var layer = new cc.LayerColor(cc.color(0, 0, 0, 150) );
        this.addChild(layer,1);
        let winbg = cc.Sprite.create(res.winbg);
        layer.setLocalZOrder(1000000);
        layer.addChild(winbg,1);
        winbg.x = size.width / 2;
        winbg.y = size.height/2; 
        cc.audioEngine.playEffect(res.win);    
        this.scheduleOnce(this.onReStartGame,5)
    },
    showLose:function(){
        let size = cc.winSize;
        var layer = new cc.LayerColor(cc.color(0, 0, 0, 150) );
        this.addChild(layer,1);
        let losebg = cc.Sprite.create(res.losebg);
        layer.setLocalZOrder(1000000);
        layer.addChild(losebg,1);
        losebg.x = size.width / 2;
        losebg.y = size.height/2;
        cc.audioEngine.playEffect(res.lose);  
        this.scheduleOnce(this.onReStartGame,5)
    }
});

//游戏场景
var GameScene = cc.Scene.extend({
    ctor : function () {
        this._super();
        cc.view.setDesignResolutionSize(1920,1080,cc.ResolutionPolicy.FIXED_WIDTH);
    },
    onEnter : function () {
        this._super();    
        var game = new GameLayer();
        this.addChild(game);
    }
});